package com.pub.check.logon;

import com.pub.tools.PropertyBean;
import javax.naming.directory.DirContext;
import java.util.Hashtable;
import javax.naming.directory.InitialDirContext;

class ActiveDirectoryCheck {

    private String[] gstrADServerAlias=null;
    private String gstrUserId=null;
    private String gstrUserPasswords=null;
    private boolean gblnDebug=false;

    private final String gstrADServerURLPrefix="_AD_URL";
    private final String gstrADServerConPrefix="_AD_CON";

    protected ActiveDirectoryCheck(String pstrADServerList,String pstrADServerListSeparateSingle,boolean pblnDebug) throws Exception{
        if(pstrADServerList==null || pstrADServerList.trim().equals("")){
            throw new Exception("ad server alias list is empty!!");
        }
        if(pstrADServerListSeparateSingle==null || pstrADServerListSeparateSingle.trim().equals("")){
            throw new Exception("ad server alias list separate is empty!!");
        }

        gstrADServerAlias = pstrADServerList.split(pstrADServerListSeparateSingle);

        gblnDebug=pblnDebug;
    }

    protected boolean validation(String pstrUserId,String pstrUserPasswords) throws Exception{
        PropertyBean lptyDBConfig= new PropertyBean("DB_Config");
        StringBuffer lstbADServerURLName=new StringBuffer();
        StringBuffer lstbADServerConName=new StringBuffer();

        this.gstrUserId=pstrUserId;
        this.gstrUserPasswords=pstrUserPasswords;

        //因當passwords為空白時，丟入ad context validation是可以過的，所以在驗證前就要先把passwords是空白的情況給過濾掉
        if(this.gstrUserId==null || this.gstrUserId.trim().equals("") || this.gstrUserPasswords==null || this.gstrUserPasswords.trim().equals("")){
            if(this.gblnDebug){System.out.println("user name or passwords is empty!!!");}
            throw new Exception("login fail");
        }

        for(int i=0;i<this.gstrADServerAlias.length;i++){
            if(this.gblnDebug){System.out.println("now check ad server==>" + gstrADServerAlias[i]);}
            lstbADServerURLName.append(gstrADServerAlias[i]);
            lstbADServerURLName.append(gstrADServerURLPrefix);

            lstbADServerConName.append(gstrADServerAlias[i]);
            lstbADServerConName.append(gstrADServerConPrefix);

            if(checkActiveDirectory(lptyDBConfig.getString(lstbADServerURLName.toString()),lptyDBConfig.getString(lstbADServerConName.toString()))){
                return true;
            }
            else{
                lstbADServerURLName.delete(0,lstbADServerURLName.length());
                lstbADServerConName.delete(0,lstbADServerConName.length());
            }
        }
        return false;
    }

    private boolean checkActiveDirectory(String pstrADServerURL,String pstrADServerCon){
        StringBuffer lstbSecPrincipal=new StringBuffer();

        lstbSecPrincipal.append("cn=");
        lstbSecPrincipal.append(this.gstrUserId);
        lstbSecPrincipal.append(",");
        lstbSecPrincipal.append(pstrADServerCon);

        DirContext ctx = null;
        Hashtable<String,String> env = new Hashtable<String,String>();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(javax.naming.Context.PROVIDER_URL, pstrADServerURL);
        env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(javax.naming.Context.SECURITY_PRINCIPAL,
                lstbSecPrincipal.toString());
        env.put(javax.naming.Context.SECURITY_CREDENTIALS, this.gstrUserPasswords);

        try{
            ctx = new InitialDirContext(env);
            return true;
        }
        catch(Exception e){
            return false;
        }
        finally{
            lstbSecPrincipal=null;

            try{ctx.close();}catch(Exception e){}
            ctx=null;

            env.clear();
            env=null;
        }
    }
}
